using AnalyStock.DataManage;

namespace AnalyStock.GrapImage;

/// <summary>
///     初始化鼠标菜单，添加或删除自选股
/// </summary>
public partial class ChartKline : UserControl
{

    public bool IsAddSeleStockMenuItem = false;
    /// <summary>
    /// 自选股菜单处理，自选股概念记录面板
    /// </summary>
    private void InitializeMenu_SeleStockNote()
    {
        AddSeleStockNotePanel.InitializeMouseDarg(this);
        AddSeleStockNotePanel.Visibility = Visibility.Hidden;
        BtnAddStockNote.Click += (s, e) =>
       {
           UpdateStockNoteAsync().WithCapturaException();
           AddSeleStockNotePanel.Visibility = Visibility.Hidden;
       };
        BtnCancelStockNote.Click += (s, e) =>
        {
            TextBoxStockNote.Text = string.Empty;
            AddSeleStockNotePanel.Visibility = Visibility.Hidden;
        };
        //股票集合数据加载完毕后，填充菜单项-概念集合
        SeleStocksFilled += CreateSeleStockMenu;
    }
    private void CreateSeleStockMenu(object sender,
                                     (IList<SelectStock>, IList<Conception> Conceptions) seleStocks)
    {
        ContextMenu _contextMenu = new()
        {
            Style = SetElementStyle("ContextMenuStyle")
        };

        //如果非概念分类窗口，禁止使用该功能
        if (IsAddSeleStockMenuItem)
        {
            MenuItem menuItem_Add = new()
            {
                Header = "🔸添加自选股",
                ToolTip = "▷",
                Name = "Add",
                Style = SetElementStyle("MenuItemStyle")
            };
            seleStocks.Conceptions?.ForEach(item =>
            {
                MenuItem menuItem_Conception = new()
                {
                    Header = item.Name,
                    ToolTip = item.OrderID,
                    Name = "Add",
                    Style = SetElementStyle("MenuItemStyle")
                };
                menuItem_Conception.Click += UpdateSeleStock;
                menuItem_Add.Items.Add(menuItem_Conception);
            });
            //子菜单：删除自选股
            MenuItem menuItem_Del = new()
            {
                Header = "🔸删除自选",
                Name = "Dele",
                Style = SetElementStyle("MenuItemStyle")
            };
            menuItem_Del.Click += UpdateSeleStock;
            //子菜单：添加概念分类
            MenuItem menuItem_Classify = new()
            {
                Header = "🔸概念分类",
                Name = "Classify",
                Style = SetElementStyle("MenuItemStyle")
            };
            menuItem_Classify.Click += (s, e) =>
            {
                ConceptionClassifyPanel.Visibility = Visibility.Visible;
            };
            _contextMenu.Items.Add(menuItem_Add);
            _contextMenu.Items.Add(menuItem_Del);
            _contextMenu.Items.Add(menuItem_Classify);
        }
        //子菜单：添加自选股的产品、概念题材说明
        MenuItem menuItem_StockNote = new()
        {
            Header = "🔸股票说明",
            Name = "Note",
            Style = SetElementStyle("MenuItemStyle")
        };
        menuItem_StockNote.Click += (s, e) =>
        {
            TextBoxStockNote.Text = currStockInfo?.Note;
            AddSeleStockNotePanel.Visibility = Visibility.Visible;
        };
        _contextMenu.Items.Add(menuItem_StockNote);
        ContextMenu = _contextMenu;
    }

    //自选股或分类概念更新后，触发以实现其他窗口相关数据的更新
    internal event EventHandler<SelectStock> SeleStockChanged;
    protected void OnSeleStockChanged(SelectStock sele)
    {
        SeleStockChanged?.Invoke(null, sele);
        ChangeCurrentStock(sele?.Ts_code, sele?.Conception);
    }

    private void UpdateSeleStock(object sender, RoutedEventArgs e)
    {
        UpdateSeleStockAsync(sender).WithCapturaException();
    }

    private async Task UpdateSeleStockAsync(object sender)
    {
        var _currMenuItem = sender as MenuItem;
        if (currStockInfo is null) return;
        var _currSele = SelectStocks?.FirstOrDefault(
                                  n => n.Ts_code.Equals(currStockInfo.Ts_code)
                                    && n.Conception.Equals(currStockInfo.Conception));
        switch (_currMenuItem)
        {
            case { Name: "Add" }://修改概念分类 
                _currSele = new()
                {
                    Id = 0,
                    Ts_code = currStockInfo.Ts_code,
                    Name = currStockInfo.Name,
                    Industry = currStockInfo.Industry,
                    Conception = (string)_currMenuItem.Header,
                    OrderID = $"{(string)_currMenuItem.ToolTip}-{GetMaxOrderId()}",
                };
                SelectStocks.Add(_currSele);
                await CommDataMethod<SelectStock>
                        .UpdateSeleStockAsync([_currSele]);
                break;
            case { Name: "Dele" }://删除自选股
                if (_currSele is null)
                {
                    "非自选股或不在概念分类页面中，不能删除...".ErrorMessage();
                    return;
                }
                if (!"是否确认删除该自选股?".IsConfirmMessage())
                {
                    return;
                }
                SelectStocks.Remove(_currSele);
                await CommDataMethod<SelectStock>
                       .DelSeleStockAsync([_currSele]);
                _currSele = null;
                break;
        }

        OnSeleStockChanged(_currSele);
        //改变面板股票名称、代码提示
        TextHeaderItem();
        //传递股票改变状态，传播事件       

        string GetMaxOrderId()
        {
            var _maxStringId = SelectStocks?
                            .Where(n => n.Conception.Equals((string)_currMenuItem.Header))
                            .Max(n => n.OrderID);
            if (string.IsNullOrEmpty(_maxStringId)) return "00";
            var _maxId = int.Parse(_maxStringId.Split("-").Last());
            return _maxId + 1 < 10 ? $"0{_maxId + 1}" : $"{_maxId + 1}";
        }
    }

    private async Task UpdateStockNoteAsync()
    {
        if (!"是否确认保存注释?".IsConfirmMessage())
        {
            return;
        }
        var _stockNote = StockNotes?.FirstOrDefault(n => n.Ts_code.Equals(currStockInfo.Ts_code));
        if (_stockNote is null)
        {
            _stockNote = new StockNote
            {
                Ts_code = currStockInfo.Ts_code,
                Name = currStockInfo.Name
            };
            StockNotes.Add(_stockNote);
        }
        //修订备注
        _stockNote.Note = TextBoxStockNote.Text.Trim();
        await CommDataMethod<StockNote>
                .SaveStockNoteAsync([_stockNote]);
        currStockInfo.Note = _stockNote.Note;
        TextHeaderItem();
    }
}